/**未遂事故的列表页面 */
<template>

  <div class="app-container">

    <div class="filter-container">
      实施单题目：   <el-input v-model="listQuery.workOrderTitle" placeholder="题目" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

      <!--<el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>
    <div>
      <!-- Note that row-key is necessary to get a correct row order. -->
      <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">

        <el-table-column width="180px" align="center" label="实施工单编号" prop="workOderId">
          <template slot-scope="scope">
            <span>{{ scope.row.workOderId }}</span></template>
        </el-table-column>
        <el-table-column min-width="300px" label="实施单题目">
          <template slot-scope="scope">
            <span @click="handleDetail(scope.row)">{{ scope.row.workOrderTitle }}</span></template>
        </el-table-column>
        <el-table-column min-width="300px" label="未遂事故题目">
          <template slot-scope="scope">
            <span>{{ scope.row.faultId.faultTitle }}</span></template>
        </el-table-column>
        <el-table-column width="100px" label="登录时间" prop="loginTime">

          <template slot-scope="scope">
            <span>{{ scope.row.loginTime }}</span></template>
        </el-table-column>
        <el-table-column align="center" label="实施单填写人" width="95">
          <template slot-scope="scope">
            <span @click="handleDetail(scope.row)">{{ scope.row.workOrderUserCode.userName }}</span></template>
        </el-table-column>
        <el-table-column class-name="status-col" label="实施单填写人部门" width="110">
          <template slot-scope="scope">
            <span @click="handleDetail(scope.row)">{{ scope.row.workOrderUserDep.deptName }}</span></template>
        </el-table-column>
        <el-table-column align="center" label="裁决状态" width="80" prop="">
          <template slot-scope="scope">

            <span v-if="scope.row.workOutStatus==1">申请中...</span>
            <span v-if="scope.row.workOutStatus==0">已删除</span>
            <span v-if="scope.row.workOutStatus==2">已裁决</span>
            <span v-if="scope.row.workOutStatus==3">已驳回</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="230">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="primary" size="small" @click="handledetailAll(scope.row)">报告书</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-form-item label="实施单题目" prop="workOrderTitle">
          <el-input v-model="temp.workOrderTitle" />
        </el-form-item>

        <el-form-item label="未遂事故单题目" prop="faultName">
          <el-select v-model="faultTitle" class="filter-item" placeholder="请选择未遂事故题目">
            <el-option v-for="item in faultNameList" :key="item.faultId" :label="item.faultTitle" :value="item.faultId" />
          </el-select>
        </el-form-item>

        <el-form-item label="登录时间" prop="loginTime">
          <el-date-picker v-model="temp.loginTime" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
          <!-- <el-input v-model="temp.faultTime " /> -->
        </el-form-item>

        <el-form-item label="完工时间" prop="workOrderTime">
          <el-date-picker v-model="temp.workOrderTime" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
          <!-- <el-input v-model="temp.faultTime " /> -->
        </el-form-item>
        <!-- <el-form-item label="实施单填写人">
          <el-select v-model="userName" class="filter-item" placeholder="请选择发现人">
            <el-option v-for="item in personlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="实施单填写人" prop="workOrderUserCode">

          <el-autocomplete
            v-model="userName"
            class="el-input"
            :fetch-suggestions="userSearchAsync"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelect"
          />
        </el-form-item>

        <!-- <el-form-item label="实施单填写人部门">
          <el-select v-model="deptName" class="filter-item" placeholder="Please select">
            <el-option v-for="item in deptlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="实施单填写人部门" prop="workOrderUserDep">

          <el-autocomplete
            v-model="deptName"
            class="el-input"
            :fetch-suggestions="deptSearchAsync"
            placeholder="请输入部门"
            :trigger-on-focus="false"
            @select="handleSelectTeam"
          />
        </el-form-item>

        <el-form-item label="附件上传">
          <ul>
            <div style="margin-left:100px">
              <el-upload
                v-model="file"
                class="upload-demo"
                action="http://localhost:8080/ehs_files/upload"
                :on-change="handleChange"
                :on-success="uploadfile"
              ><el-button size="big" type="primary">点击上传</el-button>

              </el-upload>
            </div>
          </ul>.

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import MarkdownEditor from '@/components/MarkdownEditor'
import { workOutList, deleteWorkOut, createWorkOut, editWorkOut, fetchAllCount, getPersonList, getDeptList, getFaultNameList } from '@/api/workout'
import Sortable from 'sortablejs'
// import { parseTime } from '@/utils'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getuserbyemp } from '@/api/user'
import { getDeptByName } from '@/api/fault'
// arr to obj, such as { CN : "China", US : "USA" }

export default {
  name: 'Fault',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }

  },
  data() {
    return {
      list: null,
      total: 0,
      file: '',
      listLoading: true,
      faultTitle: null,
      editList: null,
      deptName: null,
      userName: null,
      userId: null,
      deptId: null,
      sortable: null,
      oldList: [],
      newList: [],
      // 参数条件
      listQuery: {
        page: 1,
        limit: 20,
        faultTitle: null,
        faultLocation: null,
        startDate: null,
        endDate: null
      },
      personlist: null,
      deptlist: null,
      faultNameList: null,
      temp: {
        workOderId: null,
        loginTime: '',
        workOrderTitle: '',
        workOrderUserCode: '',
        workOrderUserDep: '',
        workOrderTime: '',
        workOutStatus: 1,
        faultIdNeed: '',
        faultName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        detail: '明细',
        detailreport: '未遂事故报告'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'faultTime', required: true, message: 'timestamp is required', trigger: 'change' }],
        loginTime: [{ required: true, message: 'loginTime is required', trigger: 'blur' }],
        workOrderTitle: [{ required: true, message: 'workOrderTitle is required', trigger: 'blur' }],

        workOrderTime: [{ required: true, message: 'workOrderTime is required', trigger: 'blur' }]
        // workOrderUserCode: [{ required: true, message: 'workOrderUserCode is required', trigger: 'blur' }],
      // workOrderUserDep: [{ required: true, message: 'workOrderUserDep is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fechData()
  },
  methods: {
    fechData() {
      getPersonList().then(response => {
        this.personlist = response.listName
      })
      getDeptList().then(response => {
        this.deptlist = response.listName
      })
      getFaultNameList().then(response => {
        this.faultNameList = response.listName
      })
      fetchAllCount().then(response => {
        this.total = response.count
      })
      workOutList(this.listQuery).then(response => {
        this.listLoading = true
        this.list = response.workoutList
        this.showList = response.workoutList
        // console.log('888888888888888' + response.ehsfaultList)
        this.listLoading = false
        // this.oldList = response.map(v => v.id)
      //  this.newList = response.map(v => v.id).slice()
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // alert(this.dialogStatus)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 问题所在：select选择后不返回数据到选择框
          const userName = this.userName
          // alert(userName)
          const deptName = this.deptName
          // alert(this.userId)

          const faultName1 = this.faultTitle
          this.temp.author = 'vue-element-admin'
          const query = { workOrderTime: this.temp.workOrderTime, loginTime: this.temp.loginTime, workOrderTitle: this.temp.workOrderTitle, faultIdneed: faultName1, userName: userName, deptName: deptName, userId: this.userId, deptId: this.deptId }
          createWorkOut(query).then(() => {
            this.list.unshift(this.temp.userName)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          // 刷新页面
          location.reload()
        }
      })
    },
    handleDownload() {

    },
    showReviewer() {

    },
    async handleSelect(u) {
      this.userName = u.userName
      this.userId = u.userId
      // alert(this.userId)
      console.log(this.userId)
    },
    async userSearchAsync(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName + '-' + r.userId
        tem_obj.userName = r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async deptSearchAsync(queryString, callback) {
      var list = []
      const { deptList } = await getDeptByName(queryString)
      deptList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.deptId + '-' + r.deptName
        tem_obj.deptName = r.deptName
        tem_obj.deptId = r.deptId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async handleSelectTeam(u) {
      this.deptName = u.deptName
      this.deptId = u.deptId
      // alert(this.deptId)
      // console.log(this.userId)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fechData()
    },
    resetTemp() {
      this.temp = {
        workOderId: null,
        loginTime: null,
        workOrderTitle: '',
        workOrderUserCode: '',
        workOrderUserDep: '',
        workOrderTime: '',
        workOutStatus: 1,
        faultIdNeed: '',
        faultName: ''
      }
    },
    handleDelete(row) {
      console.log(row)
      // alert(row.workOderId)
      deleteWorkOut(row.workOderId).then(response => {

      })
      location.reload()
    },
    handleEdit(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp1 = Object.assign({}, row1) // copy obj
      console.log('MMMMMMMMMMM' + this.temp1)
      this.temp.workOderId = this.temp1.workOderId
      // alert(this.temp.workOderId)
      this.userName = this.temp1.workOrderUserCode.userName
      this.deptName = this.temp1.workOrderUserDep.deptName
      this.temp.loginTime = this.temp1.loginTime
      this.temp.workOrderTitle = this.temp1.workOrderTitle
      this.faultTitle = this.temp1.faultId.faultTitle
      this.faultIdNeed = this.temp1.faultId.faultId
      // alert('XXXXXXXXXXXXXXXXXXXX' + this.faultIdNeed)
      this.temp.workOrderTime = this.temp1.workOrderTime
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // alert(this.dialogStatus)
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const query = { workOrderTime: this.temp.workOrderTime, loginTime: this.temp.loginTime, workOderId: query1.workOderId, workOrderTitle: query1.workOrderTitle, workOutSatus: 1, userName: this.userName, deptName: this.deptName, faultId1: this.faultIdNeed }
            editWorkOut(query).then(response => {
              this.obj = response
              this.faultId = response.faultId
              this.faultTitle = response.faultTitle
              // alert('修改成功')
            })
            // 刷新页面
            location.reload()
          }
        })
      }
    },

    handleDetail(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) // copy obj
      // alert(this.temp.workOderId)
      this.userName = this.temp.workOrderUserCode.userName
      this.deptName = this.temp.workOrderUserDep.deptName

      this.faultTitle = this.temp.faultId.faultTitle
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getHtml() {
      this.faultContent = this.$refs.markdownEditor.getHtml()
      console.log(this.faultContent)
    },
    handledetailAll(row) {
      // 指定跳转地址
      // alert(row.workOderId)
      this.$router.push({ path: '/fault/faultreport', query: { workOderId: row.workOderId }})
    },
    uploadfile(response, file, fileList) {
      this.file = response
    },
    handleChange() {},
    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
